<?php

namespace app\system\controller\product;

use app\common\controller\System;
use app\system\controller\daily\Throwable;
use hehe\Str;
use hehe\Trade;
use think\facade\Db;


class Product extends System {
    /**
     * Goods模型对象
     * @var object
     */
    protected object $model;

    protected string|array $defaultSortField = 'id,desc';

    protected array|string $preExcludeFields = ['id', 'create_time'];

    protected string|array $quickSearchField = ['code_customer', 'name'];

    public function initialize(): void {
        parent::initialize();
        $this->model = new \app\system\model\Product();
    }


    public function getCustomer(){
        $customer = db::name('customer')->alias('cus')
            ->leftJoin('product_category c', 'c.customer_id = cus.id')
            ->field('cus.*, count(c.id) as category_count')
            ->group('cus.id') // 添加分组，按照customer的id进行分组
            ->having('category_count > 0') // 使用HAVING过滤出至少有一个关联category的customer
            ->order('cus.id asc')
            ->select();

        $category = db::name('product_category')->select();

        $result = [
            'customer' => $customer,
            'category' => $category
        ];
        $this->success('', $result);
    }


    /**
     * 查看
     * @throws Throwable
     */
    public function index(): void {
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->param('select')) {
            $this->select();
        }

        list($where, $alias, $limit, $order) = $this->queryBuilder();
        $res = $this->model
            ->field($this->indexField)
//            ->with(['category'])
            ->alias('p')
            ->leftJoin('product_category c', 'p.category_id = c.id')
            ->leftJoin('supplier s', 's.id = c.supplier_id')
            ->leftJoin('customer cus', 'cus.id = c.customer_id')
            ->field('p.*, c.name_cn, c.name_en, s.corp_name_cn, cus.corp_name_ko customer_name_ko');
//            ->where($where);
        $params = $this->request->param();
        if(!empty($params['customer_id'])){
            $res = $res->where(['c.customer_id' => $params['customer_id']]);
        }
        if(!empty($params['category_id'])){
            $res = $res->where(['c.id' => $params['category_id']]);
        }
        if(!empty($params['supplier_id'])){
            $res = $res->where(['c.supplier_id' => $params['supplier_id']]);
        }
        if(!empty($params['quickSearch'])){
            $res = $res->where('p.code|p.name_customer|p.name_supplier|p.specification_supplier|p.specification_customer', 'like', "%{$params['quickSearch']}%");
        }

        $res = $res->order('p.id desc')->paginate($limit);

        $list = $res->items();

        foreach($list as &$val){
            $val['buy_price'] = empty($val['buy_price']) ? null : $val['buy_price'] / $this->multiply;
            $val['sale_price'] = empty($val['sale_price']) ? null : $val['sale_price'] / $this->multiply;
            $val['full_name_customer'] = $val['code_customer'] . ' / ' . $val['name_en'] . '(' . $val['specification_customer'] . ')';

            $val['drawing'] = empty($val['drawing']) ? [] : explode(',', $val['drawing']);
            $val['drawing_image'] = empty($val['drawing_image']) ? [] : explode(',', $val['drawing_image']);

            $val['name_supplier'] = htmlspecialchars_decode($val['name_supplier']);

        }


        $this->success('', [
            'list' => $list,
            'total' => $res->total(),
            'remark' => get_route_remark(),
        ]);
    }

    public function add(): void {
        if ($this->request->isPost()) {
            $data = $this->request->post();

            if(empty($data['code'])){
                $this->error('请输入产品编码');
            }
            $res = Db::name('product')->where(['code' => $data['code']])->find();
            if($res){
                $this->error('产品编码重复');
            }

            if(!empty($data['buy_price'])){
                $data['buy_price'] *= $this->multiply;
            }
            if(!empty($data['sale_price'])){
                $data['sale_price'] *= $this->multiply;
            }



            $data = $this->excludeFields($data);
            if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                $data[$this->dataLimitField] = $this->auth->id;
            }


            $result = false;
            $this->model->startTrans();
            try {

                $result = $this->model->save($data);
                $this->model->commit();
            } catch (Throwable $e) {
                $this->model->rollback();
                $this->error($e->getMessage());
            }
            if ($result !== false) {
                $this->success(__('Added successfully'));
            } else {
                $this->error(__('No rows were added'));
            }
        }

        $this->error(__('Parameter error'));
    }



    public function edit(): void
    {
        $id  = $this->request->param($this->model->getPk());
        $row = $this->model->find($id);
        if (!$row) {
            $this->error(__('Record not found'));
        }



        $dataLimitAdminIds = $this->getDataLimitAdminIds();
        if ($dataLimitAdminIds && !in_array($row[$this->dataLimitField], $dataLimitAdminIds)) {
            $this->error(__('You have no permission'));
        }

        if ($this->request->isPost()) {
            $data = $this->request->post();


            $data   = $this->excludeFields($data);

            $data['buy_price'] = empty($data['buy_price']) ? null : $data['buy_price'] * $this->multiply;
            $data['sale_price'] = empty($data['sale_price']) ? null : $data['sale_price'] * $this->multiply;


            $data['drawing'] = empty($data['drawing']) ? null : implode(',', $data['drawing']);
            if(empty($data['drawing_image'])){
                $data['drawing_image'] = null;
            }else{
                if(is_array($data['drawing_image'])){
                    $data['drawing_image'] = implode(',', $data['drawing_image']);
                }
            }


            $result = false;
            $this->model->startTrans();
            try {
                $result = $row->save($data);
                $this->model->commit();
            } catch (Throwable $e) {
                $this->model->rollback();
                $this->error($e->getMessage());
            }
            if ($result !== false) {
                $this->success(__('Update successful'));
            } else {
                $this->error(__('No rows updated'));
            }
        }

        $row['buy_price'] = empty($row['buy_price']) ? null : $row['buy_price'] / $this->multiply;
        $row['sale_price'] = empty($row['sale_price']) ? null : $row['sale_price'] / $this->multiply;

        $row['drawing'] = empty($row['drawing']) ? [] : explode(',', $row['drawing']);

        $row['name_supplier'] = htmlspecialchars_decode($row['name_supplier']);


        $this->success('', [
            'row' => $row
        ]);
    }































}